/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.tms.web;

import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.common.sortList.SortList;
import com.jeeplus.common.utils.excel.ObjectExcelView;
import com.jeeplus.common.utils.excel.PageData;
import com.jeeplus.modules.tms.entity.Resource;
import com.jeeplus.modules.tms.importEntity.DropDispatchImport;
import com.jeeplus.modules.tms.service.ResourceService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.tms.entity.DropDispatch;
import com.jeeplus.modules.tms.service.DropDispatchService;

/**
 * 落地配Controller
 *
 * @author dhw
 * @version 2018-01-16
 */
@Controller
@RequestMapping(value = "${adminPath}/tms/dropDispatch")
public class DropDispatchController extends BaseController {

    @Autowired
    private DropDispatchService dropDispatchService;
    @Autowired
    private ResourceService resourceService;

    @ModelAttribute
    public DropDispatch get(@RequestParam(required = false) String id) {
        DropDispatch entity = null;
        if (StringUtils.isNotBlank(id)) {
            entity = dropDispatchService.get(id);
        }
        if (entity == null) {
            entity = new DropDispatch();
        }
        return entity;
    }

    /**
     * 落地配列表页面
     */
    @RequiresPermissions("tms:dropDispatch:list")
    @RequestMapping(value = {"list", ""})
    public String list() {
        List<DropDispatch> dropDispatches = dropDispatchService.findList(new DropDispatch());
        for (DropDispatch dropDispatch:dropDispatches) {
            DropDispatch dropDispatch1 = new DropDispatch();
            dropDispatch1.setResource(dropDispatch.getResource());
            List<DropDispatch> dropDispatchelist = dropDispatchService.findList(dropDispatch1);
            if((dropDispatchelist.size())==1){
                dropDispatch.setIsrepeat("0");
            }else{
                dropDispatch.setIsrepeat("1");

            }
            dropDispatchService.save(dropDispatch);
        }
        return "modules/tms/dropDispatchList";
    }

    /**
     * 落地配列表数据
     */
    @ResponseBody
    @RequiresPermissions("tms:dropDispatch:list")
    @RequestMapping(value = "data")
    public Map<String, Object> data(DropDispatch dropDispatch, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<DropDispatch> page = dropDispatchService.findPage(new Page<DropDispatch>(request, response), dropDispatch);
        return getBootstrapData(page);
    }

    /**
     * 查看，增加，编辑落地配表单页面
     */
    @RequiresPermissions(value = {"tms:dropDispatch:view", "tms:dropDispatch:add", "tms:dropDispatch:edit"}, logical = Logical.OR)
    @RequestMapping(value = "form")
    public String form(DropDispatch dropDispatch, Model model) {
        model.addAttribute("dropDispatch", dropDispatch);
        return "modules/tms/dropDispatchForm";
    }

    /**
     * 保存落地配
     */
    @ResponseBody
    @RequiresPermissions(value = {"tms:dropDispatch:add", "tms:dropDispatch:edit"}, logical = Logical.OR)
    @RequestMapping(value = "save")
    public AjaxJson save(DropDispatch dropDispatch, Model model, RedirectAttributes redirectAttributes) throws Exception {
        AjaxJson j = new AjaxJson();
        if (!beanValidator(model, dropDispatch)) {
            j.setSuccess(false);
            j.setMsg("非法参数！");
            return j;
        }
        List<DropDispatch> dropDispatchList = dropDispatchService.findList(dropDispatch);
        if (dropDispatchList.size() == 0) {
            dropDispatchService.save(dropDispatch);//保存
            j.setSuccess(true);
            j.setMsg("保存落地配成功");
            return j;
        } else {
            int i = 1;
            for (DropDispatch dropD : dropDispatchList) {
                if ((dropD.getResource()).equals((dropDispatch.getResource()))) {
                    i++;
                }
            }
            if (!dropDispatch.getIsNewRecord()) {
                int k = 1;
                for (DropDispatch dropD : dropDispatchList) {
                    if ((dropD.getResource()).equals((dropDispatch.getResource())) && !((dropD.getId()).equals((dropDispatch.getId())))) {
                        k++;
                    }
                }
                if (k == 1) {
                    dropDispatchService.save(dropDispatch);//编辑保存
                    j.setSuccess(true);
                    j.setMsg("保存落地配成功");
                } else {
                    j.setSuccess(false);
                    j.setMsg("落地配已存在!");
                }
            } else {
                if (i == 1) {
                    dropDispatchService.save(dropDispatch);//编辑保存
                    j.setSuccess(true);
                    j.setMsg("保存落地配成功");
                } else {
                    j.setSuccess(false);
                    j.setMsg("落地配已存在!");
                }
            }
        }


        return j;
    }

    /**
     * 删除落地配
     */
    @ResponseBody
    @RequiresPermissions("tms:dropDispatch:del")
    @RequestMapping(value = "delete")
    public AjaxJson delete(DropDispatch dropDispatch, RedirectAttributes redirectAttributes) {
        AjaxJson j = new AjaxJson();
        dropDispatchService.delete(dropDispatch);
        j.setMsg("删除落地配成功");
        return j;
    }

    /**
     * 批量删除落地配
     */
    @ResponseBody
    @RequiresPermissions("tms:dropDispatch:del")
    @RequestMapping(value = "deleteAll")
    public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
        AjaxJson j = new AjaxJson();
        String idArray[] = ids.split(",");
        for (String id : idArray) {
            dropDispatchService.delete(dropDispatchService.get(id));
        }
        j.setMsg("删除落地配成功");
        return j;
    }

    /**
     * 导出excel文件
     */
    @ResponseBody
    @RequiresPermissions("tms:dropDispatch:export")
    @RequestMapping(value = "export", method = RequestMethod.POST)
    public AjaxJson exportFile(DropDispatch dropDispatch, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        AjaxJson j = new AjaxJson();
        try {
            String fileName = "落地配" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
            Page<DropDispatch> page = dropDispatchService.findPage(new Page<DropDispatch>(request, response, -1), dropDispatch);
            new ExportExcel("落地配", DropDispatch.class).setDataList(page.getList()).write(response, fileName).dispose();
            j.setSuccess(true);
            j.setMsg("导出成功！");
            return j;
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("导出落地配记录失败！失败信息：" + e.getMessage());
        }
        return j;
    }

    /**
     * 导入Excel数据
     */
    @RequiresPermissions("tms:dropDispatch:import")
    @RequestMapping(value = "imports", method = RequestMethod.POST)
    public String importFiles(MultipartFile file, RedirectAttributes redirectAttributes) {
        try {
            int successNum = 0;
            int failureNum = 0;
            StringBuilder failureMsg = new StringBuilder();
            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<DropDispatch> list = ei.getDataList(DropDispatch.class);
            for (DropDispatch dropDispatch : list) {
                try {
                    dropDispatchService.save(dropDispatch);
                    successNum++;
                } catch (ConstraintViolationException ex) {
                    failureNum++;
                } catch (Exception ex) {
                    failureNum++;
                }
            }
            if (failureNum > 0) {
                failureMsg.insert(0, "，失败 " + failureNum + " 条落地配记录。");
            }
            addMessage(redirectAttributes, "已成功导入 " + successNum + " 条落地配记录" + failureMsg);
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入落地配失败！失败信息：" + e.getMessage());
        }
        return "redirect:" + Global.getAdminPath() + "/tms/dropDispatch/?repage";
    }

    /**
     * 下载导入落地配数据模板
     */
    @RequiresPermissions("tms:dropDispatch:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
        try {
            String fileName = "落地配数据导入模板.xlsx";
            List<DropDispatch> list = Lists.newArrayList();
            new ExportExcel("落地配数据", DropDispatch.class, 1).setDataList(list).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
        }
        return "redirect:" + Global.getAdminPath() + "/tms/dropDispatch/?repage";
    }

    /**
     * 落地配导出数据
     */
    @RequestMapping(value = "exportdrop")
    public ModelAndView export(DropDispatch dropDispatch, String ids, HttpServletRequest request, HttpServletResponse response) {

        List<DropDispatch> dropDispatchList = new ArrayList<DropDispatch>();

        if (StringUtils.isNotEmpty(ids)) {
            String idArray[] = ids.split(",");
            for (String id : idArray) {
                dropDispatchList.add(dropDispatchService.get(id));
            }
        } else {
            dropDispatchList = dropDispatchService.findList(dropDispatch);
        }
        try {
            Map<String, Object> dataMap = new HashMap<String, Object>();
            List<String> titles = new ArrayList<String>();
            //添加订单签收标题
            titles.add("公司名称");
            titles.add("仓库面积");
            titles.add("作业时间");
            titles.add("日作量（吨/天）");
            titles.add("团队人数");
            titles.add("雨天作业");
            titles.add("自有车辆（台）");
            titles.add("网络类型");
            titles.add("是否置顶");
            titles.add("置顶到期日期");
            titles.add("录入日期");
            titles.add("修改日期");
            dataMap.put("titles", titles);

            List<PageData> excelList = new ArrayList<PageData>();
            //添加表内容
            for (DropDispatch dd : dropDispatchList) {
                PageData map = new PageData();
                map.put("var1", dd.getResource().getName());
                if (StringUtils.isNotEmpty(dd.getArea())) {
                    map.put("var2", dd.getArea());
                } else {
                    map.put("var2", "");
                }
                if (StringUtils.isNotEmpty(dd.getTaskDate())) {
                    if (dd.getTaskDate().equals("0")) {
                        map.put("var3", "24h");
                    }
                    if (dd.getTaskDate().equals("1")) {
                        map.put("var3", "白天");
                    }
                } else {
                    map.put("var3", "");
                }
                if (StringUtils.isNotEmpty(dd.getWorkload())) {
                    map.put("var4", dd.getWorkload());
                } else {
                    map.put("var4", "");
                }
                if (StringUtils.isNotEmpty(dd.getTeamAmount())) {
                    map.put("var5", dd.getTeamAmount());
                } else {
                    map.put("var5", "");
                }
                if (StringUtils.isNotEmpty(dd.getRainTask())) {
                    if (dd.getRainTask().equals("0")) {
                        map.put("var6", "可以");
                    }
                    if (dd.getRainTask().equals("1")) {
                        map.put("var6", "不可以");
                    }
                } else {
                    map.put("var6", "");
                }
                if (StringUtils.isNotEmpty(dd.getOwnTruck())) {
                    map.put("var7", dd.getOwnTruck());
                } else {
                    map.put("var7", "");
                }
                if (StringUtils.isNotEmpty(dd.getNetworkType())) {
                    if (dd.getNetworkType().equals("0")) {
                        map.put("var8", "自有");
                    }
                    if (dd.getNetworkType().equals("1")) {
                        map.put("var8", "协作");
                    }
                } else {
                    map.put("var8", "");
                }
                if (StringUtils.isNotEmpty(dd.getTop())) {
                    if (dd.getTop().equals("0")) {
                        map.put("var9", "否");
                    }
                    if (dd.getTop().equals("1")) {
                        map.put("var9", "是");
                    }
                } else {
                    map.put("var9", "");
                }
                if ((dd.getTopDate()) != null) {
                    map.put("var10", DateUtils.formatDate(dd.getTopDate(), "yyyy-MM-dd HH:mm:ss"));
                } else {
                    map.put("var10", "");
                }
                if ((dd.getCreateDate()) != null) {
                    map.put("var11", DateUtils.formatDate(dd.getCreateDate(), "yyyy-MM-dd HH:mm:ss "));
                } else {
                    map.put("var11", "");
                }
                if ((dd.getUpdateDate()) != null) {
                    map.put("var12", DateUtils.formatDate(dd.getUpdateDate(), "yyyy-MM-dd HH:mm:ss "));
                } else {
                    map.put("var12", "");
                }
                excelList.add(map);
            }
//            dataMap.put("excelList", excelList);

            String fileName = "落地配" + DateUtils.formatDate(new Date(), "yyyy-MM-dd");
            dataMap.put("fileName", fileName);

            dataMap.put("excelList", excelList);
            System.out.println("===导出excel成功！");
            ObjectExcelView erv = new ObjectExcelView();                    //执行excel操作

            return new ModelAndView(erv, dataMap);

        } catch (Exception e) {
            System.out.println("======导出excel时出错！" + e.getMessage());
        }
        return new ModelAndView("redirect:" + Global.getAdminPath() + "/tms/dropDispatchList");
    }

    /**
     * 导入Excel数据
     */
    @RequiresPermissions("tms:dropDispatch:import")
    @RequestMapping(value = "import", method = RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        try {
            int successNum = 0;
            int failureNum = 0;
            StringBuilder failureMsg = new StringBuilder();
            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<DropDispatchImport> newList = ei.getDataList(DropDispatchImport.class);
            for (DropDispatchImport ddi : newList) {
                try {
                    DropDispatch dropDispatch = new DropDispatch();
                    if (StringUtils.isNotEmpty(ddi.getResource())) {
                        Resource resourse = new Resource();
                        resourse.setName(ddi.getResource());
                        List<Resource> resourseList = resourceService.findList(resourse);
                        SortList<Resource> msLists = new SortList<Resource>();     //调用工具类，按照指定字段排序
                        msLists.sortByMethod(resourseList, "getCreateDate", false);
                        dropDispatch.setResource(resourseList.get(0));
                    }
                    if (StringUtils.isNotEmpty(ddi.getArea())) {
                        dropDispatch.setArea(ddi.getArea());
                    }
                    if (StringUtils.isNotEmpty(ddi.getTaskDate())) {
                        if ("24h".equals(ddi.getTaskDate())) {
                            dropDispatch.setTaskDate("0");
                        } else if ("白天".equals(ddi.getTaskDate())) {
                            dropDispatch.setTaskDate("1");
                        } else {
                            dropDispatch.setTaskDate("");
                        }
                    }
                    if (StringUtils.isNotEmpty(ddi.getWorkload())) {
                        dropDispatch.setWorkload(ddi.getWorkload());
                    }
                    if (StringUtils.isNotEmpty(ddi.getTeamAmount())) {
                        dropDispatch.setTeamAmount(ddi.getTeamAmount());
                    }
                    if (StringUtils.isNotEmpty(ddi.getRainTask())) {
                        if (ddi.getRainTask().equals("可以")) {
                            dropDispatch.setRainTask("0");
                        } else if (ddi.getRainTask().equals("不可以")) {
                            dropDispatch.setRainTask("1");
                        } else {
                            dropDispatch.setRainTask("");
                        }
                    }
                    if (StringUtils.isNotEmpty(ddi.getOwnTruck())) {
                        dropDispatch.setOwnTruck(ddi.getOwnTruck());
                    }
                    if (StringUtils.isNotEmpty(ddi.getNetworkType())) {
                        if (ddi.getNetworkType().equals("自有")) {
                            dropDispatch.setNetworkType("0");
                        } else if (ddi.getNetworkType().equals("协作")) {
                            dropDispatch.setNetworkType("1");
                        } else {
                            dropDispatch.setNetworkType("");
                        }

                    }
                    if (StringUtils.isNotEmpty(ddi.getTop())) {
                        if (ddi.getTop().equals("否")) {
                            dropDispatch.setTop("0");
                        } else if (ddi.getTop().equals("是")) {
                            dropDispatch.setTop("1");
                        } else {
                            dropDispatch.setTop("");
                        }

                    }
                    if ((ddi.getTopDate()) != null) {
                        dropDispatch.setTopDate(df.parse(ddi.getTopDate()));
                    }
                    dropDispatchService.save(dropDispatch);
                    successNum++;
                } catch (ConstraintViolationException ex) {
                    failureNum++;
                } catch (Exception ex) {
                    failureNum++;
                }
            }
            if (failureNum > 0) {
                failureMsg.insert(0, "，失败 " + failureNum + " 条订单记录。失败原因例如：导入数据出错！");
            }
            addMessage(redirectAttributes, "已成功导入 " + successNum + " 条订单记录" + failureMsg);
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入订单失败！失败信息：" + e.getMessage());
        }
        return "redirect:" + Global.getAdminPath() + "/tms/dropDispatch/?repage";
    }
}